package com.bootdo.acitvity.listener.message.event.component;

import com.bootdo.acitvity.listener.message.event.message.EventBus;
import com.bootdo.acitvity.listener.message.event.message.EventSubscriber;
import com.bootdo.acitvity.listener.message.event.orderEvent.OrderEvent;
import com.bootdo.acitvity.listener.message.handle.EventHandle;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Getter
@Setter
public class EventComponent implements EventSubscriber {

    private EventBus eventBus;

    private static Map<Class<?>, Map<Class<?>, EventHandle>> handlerMap = new ConcurrentHashMap<>();


    @Override
    public void update(List<OrderEvent> events) {
        for (OrderEvent event : events) {
            Map<Class<?>, EventHandle> eventMap = handlerMap.get(this.getClass());
            if (eventMap!=null&&eventMap.size()>0) {
                EventHandle handler = eventMap.get(event.getClass());
                if (Objects.nonNull(handler)) {
                    handler.handleEvent(event);
                }
            }
        }
    }

    @Override
    public void subscribe(EventBus eventBus) {
        this.eventBus = eventBus;
        eventBus.registerSubscriber(this);
    }

    public void addHandle(EventHandle eventHandle){
        Map<Class<?>, EventHandle> classEventHandleMap = handlerMap.get(this.getClass());
        if(classEventHandleMap==null){
            classEventHandleMap = new HashMap<>();
            handlerMap.put(this.getClass(), classEventHandleMap);
        }
        classEventHandleMap.put(eventHandle.getEventType(), eventHandle);
    }

    public void publishEvent(List<OrderEvent> orderEvents){
        eventBus.publishEvent(this.getClass(), orderEvents);
    }

}
